package cn.kgc.jdbc;

import cn.kgc.entity.User;

import java.sql.*;

/**
 * @author mosin
 * date 2022/2/10
 * @version 1.0
 *
 *获取插入数据的自增id值
 *
 */
public class JDBCDemo04 {

    public static void main(String[] args) {
        Connection connection = null;
        Statement stmt = null;
        try {
            //1.注册驱动  方式2  类加载  反射   推荐
            Class.forName("com.mysql.jdbc.Driver");
            //2.获取连接
            String  url = "jdbc:mysql://localhost:3306/java2114";
            String username = "root";
            String password = "root";
            connection = DriverManager.getConnection(url,username,password);
            //3. 生成操作数据库的对象
            stmt = connection.createStatement();
            // 4.编写sql  发送sql  DML insert  delete  update
            User user = new User();
            user.setRole(1);
            user.setPwd("888888");
            user.setUsername("mayun");
            String sql = "insert into user(username,pwd,role)values('"+user.getUsername()+"','"+user.getPwd()+"',"+user.getRole()+")";
            System.out.println("sql = " + sql);
            // 5. 处理结果集  DQL
            int line = stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
            ResultSet rs = stmt.getGeneratedKeys();
            if(rs.next()){
                int id = rs.getInt(1);
                System.out.println("主键id = " + id);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {  // 6. 释放资源

            try {
                if(stmt!=null){
                    stmt.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            try {
                if(connection!=null){
                    connection.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

    }

}

